<template>
  <div class="addDispatch-dialog">
    <el-dialog
      title="创建发运计划"
      :close-on-click-modal="false"
      :visible.sync="addDispatchVisible">
      <el-form
        label-width="115px"
        ref="addDispatchPlanForm"
        :model="addDispatchPlanForm"
      >
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="业务编号:" prop="codes">
              <el-input placeholder="XS20200910001" :disabled="true" v-model="viewForm.codes"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item v-if="this.processType === 1 || this.processType === 3 || this.processType === 4 || this.processType === 5" label="客户名称:" prop="companyName">
              <el-input placeholder="往来单位名称" :disabled="true" v-model="viewForm.companyName"></el-input>
            </el-form-item>
            <el-form-item v-if="this.processType === 2 || this.processType === 6" label="供应商名称:" prop="companyName">
              <el-input placeholder="往来单位名称" :disabled="true" v-model="viewForm.companyName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="货物:" prop="productId"
                :rules="[{ required: true, message: '请选择货物', trigger: 'change' }]"
            >
              <el-select clearable v-model="addDispatchPlanForm.productId" placeholder="请选择" @change="setDefaultPrice">
                <el-option
                  v-for="item in productData"
                  :key="item.productId"
                  :label="item.productName"
                  :value="item.productId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发运期间:" prop="value1"
                :rules="[{ required: true, message: '请选择发运期间', trigger: 'change' }]"
            >
              <el-date-picker
                v-model="addDispatchPlanForm.value1"
                @change="changeHandlerPlanDate"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="本次运量:" prop="transQuantity" class="current-volume"
                :rules="[{ required: true, message: '请输入本次运量', trigger: 'blur' }]"
            >
              <el-input class="adjustInputAppend show" v-model="addDispatchPlanForm.transQuantity" placeholder="">
                  <span slot="suffix">吨</span>
              </el-input>
              <span class="note">未发运{{this.surpQuantity}}吨</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="moreContent">
            <el-form-item label="车数:" prop="axle" class="hasMoreItem ">
              <el-select clearable v-model="addDispatchPlanForm.axle" placeholder="请选择">
                <el-option
                  v-for="item in carNums"
                  :key="item.id"
                  :label="item.axle"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
              <el-form-item prop="truckNumPlanned"  :rules="[{validator:validator.isPositiveInteger, trigger:'blur'}]">
              <el-input class="adjustInputAppend" v-model="addDispatchPlanForm.truckNumPlanned">
                <span slot="suffix">车</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="亏吨单价:" prop="lossPrice"
                :rules="[{ required: true, message: '请输入默认货物单价', trigger: 'blur' }]"
            >
              <el-input class="adjustInputAppend show" placeholder="默认货物单价" v-model="addDispatchPlanForm.lossPrice">
                <span slot="suffix">元/吨</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运费单价:" prop="transPrice">
              <el-input class="adjustInputAppend show" placeholder="请输入价格" v-model="addDispatchPlanForm.transPrice">
                <span slot="suffix">元/吨</span>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="发货地址:" prop="sendAddress"
                :rules="[{ required: true, message: '请选择发货地址', trigger: 'blur' }]"
            >
              <el-input placeholder="请选择发货地址" class="selectInput" v-model="addDispatchPlanForm.sendAddress" size="small" @focus="getCompanyAddressClient">
<!--                <template slot="append"><span @click="getCompanyAddressClient">选择</span></template>-->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" class="moreContent">
              <el-form-item label="发货联系人:" prop="transContact" class="hasMoreItem"
                            :rules="[{ required: true, message: '请输入发货人', trigger: 'blur' }]"
              >

                  <el-input placeholder="请输入发货人" v-model="addDispatchPlanForm.transContact"></el-input>
              </el-form-item>
              <el-form-item prop="transPhone" :rules="[{ required: true, message: '请输入发货人电话', trigger: 'blur' }]">
                  <el-input placeholder="请输入发货人电话" v-model="addDispatchPlanForm.transPhone"></el-input>

              </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="收货地址:" prop="receiveAddress"
                          :rules="[{ required: true, message: '请选择收货地址', trigger: 'blur' }]"
            >
              <el-input placeholder="请选择收货地址" class="selectInput" v-model="addDispatchPlanForm.receiveAddress" size="small" @focus="getReceiveAddressClient">
<!--                <template slot="append"><span @click="getReceiveAddressClient">选择</span></template>-->
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"  class="moreContent">
              <el-form-item label="收货联系人:" class="hasMoreItem" prop="receiveContact"
                            :rules="[{ required: true, message: '请输入收货人', trigger: 'blur' }]"
              >
                  <el-input placeholder="请输入收货人" v-model="addDispatchPlanForm.receiveContact"></el-input>
              </el-form-item>
              <el-form-item prop="receivePhone" :rules="[{ required: true, message: '请输入收货人电话', trigger: 'blur' }]">
                  <el-input placeholder="请输入收货人电话" v-model="addDispatchPlanForm.receivePhone"></el-input>
              </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="运费结算依据:">
              <el-select clearable v-model="addDispatchPlanForm.transMoneyBasis"  placeholder="请选择">
                <el-option
                  v-for="item in  $dictUtils.getDictList('transMoneyBasis')"
                  :key="item.value"
                  :label="item.label"
                  :value="Number(item.value)">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行期间:" prop="value2" :rules="[{ required: true, message: '请选择发运期间', trigger: 'change' }]">
              <el-date-picker
                v-model="addDispatchPlanForm.value2"
                @change="changeHandlerExecuteDate"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="30">
          <el-col :span="12">
            <el-form-item label="装车时限:" prop="effectiveHourLoad">
              <el-input @input="(e)=>checkInput(e,'effectiveHourLoad')" clearable class="adjustInputAppend" v-model="addDispatchPlanForm.effectiveHourLoad" maxlength="3"
                        v-filter-special-char="addDispatchPlanForm.effectiveHourLoad" placeholder="请输入接单到装货的限制时长">
                <span slot="suffix" class="">小时</span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="mode==2">
          	<el-form-item label="接单后生效:" prop="afterOrderEnabled">
	          	<el-radio-group v-model="afterOrderEnabled">
						    <el-radio :label="0">是</el-radio>
						    <el-radio :label="1">否</el-radio>
				 	 		</el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="hasPermission('transportPlan:plan:add')" @click="doSubmit">确认</el-button>
        <el-button class="save" @click="doSave">提交</el-button>
        <el-button @click="addDispatchVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!--发货地址选择弹窗-->
    <CompanyAddressDialog ref="CompanyAddressDialog" @getCompanyAddressData="getCompanyAddressData">

    </CompanyAddressDialog>
    <!--收货地址选择弹窗-->
    <ReceiveAddressDialog ref="ReceiveAddressDialog" @getReceiveAddressData="getReceiveAddressData">

    </ReceiveAddressDialog>
  </div>
</template>

<script>
  import { getAxleList } from '@/api/truck/truckAxle.js'
  import CompanyAddressDialog from '@/components/dialog/companyAddressDialog.vue'
  import ReceiveAddressDialog from '@/components/dialog/receiveAddressDialog.vue'
  import { savePlan, getProductList, getAddressList, queryById, getDefaultPrice } from '@/api/transplan/transplan.js'
    export default {
        name: 'addDispatchPlanForm',
      components: {
        CompanyAddressDialog,
        ReceiveAddressDialog
      },
      props:{
      	mode:{
      		type:[String,Number],
      		default:1
      	}
      },
      data () {
        return {
          input: '',
          addDispatchVisible: false,
          cargos: [],
          cargosValue: '',
          value1: '',
          value2: '',
          carNums: [],
          car: '',
          shipAddresses: [],
          shipAddress: '',
          receivingAddresses: [],
          receivingAddress: '',
          productData: [],
          businessId: '',
          productId: '',
          viewForm: {
            codes: '',
            companyName: '',
            transQuantity: ''
          },
          page: {
            pageSize: 10,
            pageNo: 1,
            total: 0
          },
          afterOrderEnabled:1,//接单后生效or直接生成运单
          addDispatchPlanForm: {
              value1: '',
              value2: '',
            productId: '',
            sendStartDate: '',
            sendEndDate: '',
            execStartDate: '',
            execEndDate: '',
            transQuantity: '',
            businessId: '',
            truckNumPlanned: 0,
            axle: '',
            lossPrice: '',
            transPrice: '',
            receiveContact: '',
            receivePhone: '',
            transContact: '',
            transPhone: '',
            transMoneyBasis: '',
            receiveAddress: '',
            sendAddress: '',
            state: '',
            effectiveHourLoad:24
          },
          surpQuantity: 0,
          processType: '',
          props1: '',
          companyId1: '',
          props2: '',
          companyId2: ''
        }
      },
      methods: {
      	handleClose(done) {
					this.$Msg.confirm({
						title:'您确定要关闭吗？',
						content:this.GLOBAL.FORM_CLOSE_TIPS,
						confirmCall:()=>{
							done();
						}
					})
				},
				// 小数点后两位
	      limitDecimals (value) {
	        const reg = /^(\-)*(\d+)\.(\d\d).*$/
	        if (typeof value === 'string') {
	          return !isNaN(Number(value)) ? value.replace(reg, '$1$2.$3') : ''
	        } else if (typeof value === 'number') {
	          return !isNaN(value) ? String(value).replace(reg, '$1$2.$3') : ''
	        } else {
	          return ''
	        }
	      },
	      // @input
	      checkInput (val, name) {
	        let value
	        if (name === 'truckNumPlanned' || name === 'effectiveHourLoad') {
	          value = val.replace(/^(0+)|[^\d]+/g, '')
	        } else {
	          value = this.limitDecimals(val)
	        }
	        this.$nextTick(() => {
	          this.$set(this.addDispatchPlanForm, name, value)
	        })
	      },
        // 发运日期选择
        changeHandlerPlanDate (e) {
            if (e) {
                this.addDispatchPlanForm.sendStartDate = e[0]
                this.addDispatchPlanForm.sendEndDate = e[1]
            } else {
                this.addDispatchPlanForm.sendStartDate = ''
                this.addDispatchPlanForm.sendEndDate = ''
            }
        },
        changeHandlerExecuteDate (e) {
            this.addDispatchPlanForm.execStartDate = e[0]
            this.addDispatchPlanForm.execEndDate = e[1]
        },
        getAxleList () {
          getAxleList().then(({data}) => {
            if (data.code === '200') {
              this.carNums = data.result.list
            }
            this.loading = false
          })
        },
        getProductList (businessId) {
          getProductList({
            businessId: businessId
          }).then(({data}) => {
            if (data.code === '200') {
              this.productData = data.result
            }
          })
        },
        // 发货地址选择弹窗
        getCompanyAddressClient () {
          this.$refs['CompanyAddressDialog'].init('address', this.props1, this.companyId1)
        },
        // 发货地址选择数据回显
        getCompanyAddressData (row) {
          this.addDispatchPlanForm.sendAddressId = row.id
          this.addDispatchPlanForm.sendAddress = row.detailAddress
          this.addDispatchPlanForm.transContact = row.contactName
          this.addDispatchPlanForm.transPhone = row.contactPhone
          this.dialogVisible = false
        },
        // 收货地址选择弹窗
        getReceiveAddressClient () {
          this.$refs['ReceiveAddressDialog'].init('address', this.props2, this.companyId2)
        },
        // 收货地址选择数据回显
        getReceiveAddressData (row) {
          this.addDispatchPlanForm.receiveAddress = row.detailAddress
          this.addDispatchPlanForm.receiveAddressId = row.id
          this.addDispatchPlanForm.receiveContact = row.contactName
          this.addDispatchPlanForm.receivePhone = row.contactPhone
          this.dialogVisible = false
        },
        // 默认发货地址
        getDefaultSendAddress (params) {
          getAddressList({
            pageSize: params.pageSize,
            pageNo: params.pageNo,
            props: this.props1,
            id: this.companyId1,
            isDefault: 1
          }).then((res) => {
            if (res.data.code === '200') {
              this.addDispatchPlanForm.sendAddressId = res.data.result.list[0].addressList[0].id
              this.addDispatchPlanForm.sendAddress = res.data.result.list[0].addressList[0].detailAddress
              this.addDispatchPlanForm.transContact = res.data.result.list[0].addressList[0].contactName
              this.addDispatchPlanForm.transPhone = res.data.result.list[0].addressList[0].contactPhone
            }
          })
        },
        // 获取默认收货地址
        getDefaultReceiveAddress (params) {
          getAddressList({
            pageSize: params.pageSize,
            pageNo: params.pageNo,
            id: this.companyId2,
            props: this.props2,
            isDefault: 1
          }).then((res) => {
            if (res.data.code === '200') {
              this.addDispatchPlanForm.receiveAddressId = res.data.result.list[0].addressList[0].id
              this.addDispatchPlanForm.receiveAddress = res.data.result.list[0].addressList[0].detailAddress
              this.addDispatchPlanForm.receiveContact = res.data.result.list[0].addressList[0].contactName
              this.addDispatchPlanForm.receivePhone = res.data.result.list[0].addressList[0].contactPhone
            }
          })
        },
        doSubmit () {
          this.$confirm('确认后将不可更改，是否确认？', '提示', {
            confirmButtonText: '确认',
            cancelButtonText: '取消'
          }).then((res) => {
            this.$refs['addDispatchPlanForm'].validate((valid) => {
              if (valid) {
                this.$set(this.addDispatchPlanForm, 'props', 2)
                this.addDispatchPlanForm.subType = 2
                if(this.mode==2){
                	this.$set(this.addDispatchPlanForm, 'afterOrderEnabled', this.afterOrderEnabled)
                }
                savePlan(this.addDispatchPlanForm).then(({data}) => {
                  if (data.code === '200') {
                    this.$message({
                      message: '保存发运计划成功',
                      type: 'success'
                    })
                    this.addDispatchVisible = false
                    this.$emit('refreshDataList')
                  }
                })
              }
            })
          })
        },
        setDefaultPrice () {
          if (this.addDispatchPlanForm.productId === undefined || this.addDispatchPlanForm.productId === '') {
            this.addDispatchPlanForm.lossPrice = ''
          } else {
            getDefaultPrice({
              businessId: this.businessId,
              productId: this.addDispatchPlanForm.productId
            }).then(({data}) => {
              if (data.code === '200') {
                this.addDispatchPlanForm.lossPrice = data.result.displayPrice
              }
            })
          }
        },
        doSave () {
          this.$refs['addDispatchPlanForm'].validate((valid) => {
            if (valid) {
              this.$set(this.addDispatchPlanForm, 'props', 2)
              this.addDispatchPlanForm.subType = 1
              savePlan(this.addDispatchPlanForm).then(({data}) => {
                if (data.code === '200') {
                  this.$message({
                    message: '保存发运计划成功',
                    type: 'success'
                  })
                  this.addDispatchVisible = false
                  this.$emit('refreshDataList')
                }
              })
            }
          })
        },
        init (method, row) {
          this.getAxleList()
          if (method === 'add') {
            this.businessId = row.id
            this.getProductList(row.id)
            this.addDispatchVisible = true
            this.$nextTick(() => {
              this.$refs.addDispatchPlanForm.resetFields()
              this.addDispatchPlanForm.sendStartDate = ''
              this.addDispatchPlanForm.sendEndDate = ''
              this.addDispatchPlanForm.execStartDate = ''
              this.addDispatchPlanForm.execEndDate = ''
              this.value1 = ''
              this.value2 = ''
            })
            this.processType = row.processType
            this.viewForm.transQuantity = row.transQuantity
            this.viewForm.codes = row.codes
            this.viewForm.companyName = row.companyName
            this.addDispatchPlanForm.businessId = row.id
            this.productData = row.businessProductList
            this.surpQuantity = row.surpQuantity
            if (this.processType === 1 || this.processType === 3 || this.processType === 4 || this.processType === 5) {
              this.props1 = 0
              this.companyId1 = ''
              this.props2 = ''
              this.companyId2 = row.companyId
            }
            if (this.processType === 2 || this.processType === 6) {
              this.props1 = ''
              this.companyId1 = row.companyId
              this.props2 = 0
              this.companyId2 = ''
            }
            this.getDefaultSendAddress(this.page)
            this.getDefaultReceiveAddress(this.page)
            this.title = '创建发运计划'
          } else if (method === 'edit') {
            this.title = '修改发运计划'
            this.getProductList(row.businessId)
            this.addDispatchVisible = true
            this.method = method
            this.$nextTick(() => {
              this.$refs.addDispatchPlanForm.clearValidate()
            })
            queryById({
              id: row.id
            }).then(({data}) => {
              if (data.code === '200') {
                this.addDispatchPlanForm = data.result
                this.viewForm.codes = row.business.codes
                this.viewForm.companyName = row.business.companyName
                this.addDispatchPlanForm.value1 = [this.addDispatchPlanForm.sendStartDate,this.addDispatchPlanForm.sendEndDate]
                this.addDispatchPlanForm.value2 = [this.addDispatchPlanForm.execStartDate,this.addDispatchPlanForm.execEndDate]
                this.surpQuantity = this.addDispatchPlanForm.surpQuantity
              }
            })

          }
        }
      }
    }
</script>

<style lang="scss" scoped>
.addDispatch-dialog{
  ::v-deep.el-dialog{
    width: fit-content;

    .el-dialog__header{
      padding: 0 20px !important;
      height: 41px;
      line-height: 41px;
    }

    .el-dialog__headerbtn{
      top: 11px;
    }
    .el-dialog__title{
      font-size: 16px;
      color: #333333;
    }
    .el-dialog__body{

      .el-form-item__error{
        padding-top: 4px !important;
        color: #FF3E3E;
      }
    }
    /*.el-dialog__footer{*/
    /*  .el-button.save{*/
    /*    background: #F59A23;*/
    /*    color: #FFFFFF;*/
    /*    border: 1px solid #F59A23;*/
    /*    margin-right: 5px;*/
    /*  }*/
    /*  .el-button.save+.el-button{*/
    /*    margin-right: 5px;*/
    /*  }*/
    /*  .el-button.save:hover{*/
    /*    background-color: #e98f23 !important;*/
    /*    color: #FFFFFF;*/
    /*    border: 1px solid #e98f23;*/
    /*  }*/
    /*}*/
  }
}
::v-deep.el-form{
    .el-row{
        .el-col:last-child{
            .el-form-item__label{
                width: 109px !important;
            }
            .el-form-item__content{
                margin-left: 109px !important;
            }
        }
    }
  p{
    margin: 0;
  }
  .el-input {
    input {
      width: 320px;
      /*padding: 0 10px !important;*/
    }

    input:hover, input:focus {
      border-color: #1890ff;
    }

    .el-input__inner::-webkit-input-placeholder {
      color: #999999;
    }
  }

  .current-volume{
    .el-input{
        width: inherit;
      input{
          width: 150px;
        border-right:none;
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
          padding-right: 28px !important;
          min-width: 150px !important;

      }

    }
    span.note{
      font-size: 12px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #FF3E3E;
      margin-left: 20px;
      position: relative;
      top: 6px;
    }
  }

  /*.el-form-item.hasInputAppend{*/
  /*  .el-input{*/
  /*    width: 320px;*/
  /*    input{*/
  /*      width: 279px;*/

  /*    }*/
  /*  }*/
  /*}*/

  .el-form-item{
    .el-form-item__content{
      .el-date-editor.el-input__inner{
        width: 320px;
      }
    }
  }

  .el-select{
      width: inherit !important;
    .el-input .el-select__caret{
      /*color:#666666;*/
      /*font-size: 16px;*/
    }
  }
  .el-form-item.hasMoreItem{
    .el-form-item__content{
      .el-input{
        margin-right: 10px;
        width: inherit;
        input{
          min-width: inherit !important;
          width: 150px;
        }
      }
    }
    .el-select{
      width: inherit !important;
        margin-right: 10px;
        .el-input{
            margin-right: 0 !important;
        }
    }
  }
    .el-col.moreContent{
    display: flex;
        .el-form-item:last-child{
            .el-form-item__content{
                margin-left: 0 !important;
                .el-input{
                    width: inherit;
                    input{
                        min-width: inherit;
                        width: 160px;
                    }
                }
            }
        }
        .adjustInputAppend.el-input{
            .el-input__inner{
                padding-right: 25px !important;
            }
        }
    }
}
</style>
